package com.system.controller;

import com.common.exception.BusinessException;
import com.common.res.DataResult;
import com.common.service.ValidateCodeService;
import com.system.service.UserService;
import com.system.vo.request.LoginReqVO;
import com.system.vo.request.RegisterReqVO;
import com.system.vo.response.LoginRespVO;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;

@RestController
@Api(tags = "登录管理")
public class LoginController {

    @Autowired
    private ValidateCodeService validateCodeService;
    @Autowired
    private UserService userService;

    @GetMapping("/images/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, BusinessException {
        validateCodeService.create(request, response);
    }

    @PostMapping("/login")
    public DataResult<LoginRespVO> login(@RequestBody @Valid LoginReqVO vo, HttpServletRequest request){
        DataResult result=DataResult.success();
        HttpSession session = request.getSession();
        validateCodeService.check(session.getId(),vo.getCode());
        result.setData(userService.login(vo));
        return result;
    }

    @PostMapping("/register")
    public DataResult register(@RequestBody @Valid RegisterReqVO vo){
        DataResult result=DataResult.success();
        userService.register(vo);
        return result;
    }
}
